// express 会话管理
import express from 'express';
import session from 'express-session';

const app = express();
// 设置会话
app.set('trust proxy', 1) // 信任代理
app.use(session({
  secret: 'GvY1/lw7e1lx3mQp1T42HKOaOOFLteSv8MGzignZ9JU=',
  resave: false,
  saveUninitialized: true,
  cookie: {
    secure: false,
    httpOnly: false,
    maxAge: 1000 * 60 * 60 * 24
  }
}))
// 设置 body 解析器
app.use(express.urlencoded({ extended: true }));
// 设置模板引擎
app.set("view engine", "ejs");
app.set("views", "./views");

app.get("/", (req, res) => {
  // 获取会话数据
  const username = req.session.username;
  res.render('session', { username });
})

app.get("/login", (req, res) => {
  res.send(`<form action="/login" method="post">
    <input type="text" name="username" placeholder="用户名">
    <input type="password" name="password" placeholder="密码">
    <button type="submit">登录</button>
    </form>`)
})

app.post("/login", (req, res) => {
  const { username, password } = req.body;
  if (username === "admin" && password === "123456") {
    // 登录成功，设置会话数据
    req.session.username = username;
  }
  // 重定向到首页
  res.redirect("/");
})

app.get("/logout", (req, res) => {
  req.session.destroy()
  res.redirect("/")
})

app.listen(3000, () => {
  console.log("Server running on port 3000");
})